package my_logger

import (
	"github.com/gocolly/colly/debug"
	"go.uber.org/zap"
	"sync/atomic"
	"time"
)

// LogDebugger is the simplest debugger which prints log messages to the STDERR
type LogDebugger struct {
	sugarLogger *zap.SugaredLogger
	counter     int32
	start       time.Time
}

// Init initializes the LogDebugger
func (l *LogDebugger) Init() error {
	l.counter = 0
	l.start = time.Now()
	l.sugarLogger = initLog("./logs/spider/info.log", "./logs/spider/err.log", "debug").Sugar()
	return nil
}

// Event receives Collector events and prints them to STDERR
func (l *LogDebugger) Event(e *debug.Event) {
	i := atomic.AddInt32(&l.counter, 1)
	switch e.Type {
	case "request", "response":
		l.sugarLogger.Infof("[%06d] %d [%6d - %s] %q (%s)", i, e.CollectorID, e.RequestID, e.Type, e.Values, time.Since(l.start))
	case "error":
		l.sugarLogger.Errorf("[%06d] %d [%6d - %s] %q (%s)", i, e.CollectorID, e.RequestID, e.Type, e.Values, time.Since(l.start))
	}
}

func (l *LogDebugger) Sync() {
	l.sugarLogger.Sync()
}
